import { wrapper } from '@/app/store'
import { AuthLayout } from '@/layouts/publ/AuthLayout'
import { MainLayout } from '@/layouts/publ/MainLayout'
import { getRunningQueriesThunk } from '@/services/api/api'
import { useGetMeQuery } from '@/services/authService/authEndpoints'
import { getAllPosts, getTotalCount } from '@/services/publicService/publicEndpoints'
import { Spinner } from '@/shared/ui/Spinner'
import { PublicPosts } from '@/widgets/root/publicPosts'
import { GetStaticPropsResult } from 'next'
import Head from 'next/head'

type Props = {
  isPostsError?: boolean
  isUsersError?: boolean
}

export const getStaticProps = wrapper.getStaticProps(
  store => async (): Promise<GetStaticPropsResult<Props>> => {
    const users = await store.dispatch(getTotalCount.initiate(undefined))
    const posts = await store.dispatch(getAllPosts.initiate({}))

    await Promise.all(store.dispatch(getRunningQueriesThunk()))

    if (!posts) {
      return {
        props: {
          isPostsError: true,
        },
        revalidate: 60,
      }
    }

    if (!users) {
      return {
        props: {
          isUsersError: true,
        },
        revalidate: 60,
      }
    }

    return {
      props: {},
    }
  }
)

const HomePage = ({}: Props) => {
  const { data: me, isLoading } = useGetMeQuery()

  if (isLoading) {
    return (
      <div
        style={{
          alignItems: 'center',
          display: 'flex',
          height: '100vh',
          justifyContent: 'center',
          minWidth: '100%',
        }}
      >
        <Spinner />
      </div>
    )
  }

  const content = (
    <>
      <Head>
        <title>InstaLife</title>
        <meta content={'Generated by create next app'} name={'description'} />
        <meta content={'width=device-width, initial-scale=1'} name={'viewport'} />
        <link href={'/favicon.ico'} rel={'icon'} />
      </Head>
      <div style={{ width: '100%' }}>
        <PublicPosts.widget />
      </div>
    </>
  )

  return me ? <MainLayout>{content}</MainLayout> : <AuthLayout>{content}</AuthLayout>
}

export default HomePage
